import React, {Component} from 'react'

import DefaultLoadingElement from 'lib/util/defaultLoadingElement.jsx'
import DefaultNoDataElement from 'lib/util/defaultNoDataElement.jsx'
import DefaultErrorElement from 'lib/util/defaultErrorElement.jsx'

export default class SingleInfoCell extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      animatedHeight: 0
    };
  }

  resizeAnimatedHeight() {
    if (this.props.loading || this.props.error) {
      let container = this.refs.container;
      if (container && this.state.animatedHeight === 0) {
        this.setState({animatedHeight:container.offsetHeight});
      }
    }
  }

  componentDidMount() {
    this.resizeAnimatedHeight();
  }

  componentDidUpdate(prevProps, prevState) {
    this.resizeAnimatedHeight();
  }

  renderBody() {
    let currentStyle = {};
    if (this.props.unit === '') {
      currentStyle.marginRight = '0px';
    }
    return (
      <div className="single-info-cell" style={this.props.style}>
        <div style={{padding:'11px 0 0'}}>
          <i className={'iconfont '+this.props.iconClass}>
            <span className="single-info-content-title">{this.props.title}</span>
          </i>
        </div>
        <div className="single-info-content-container">
          <span className="single-info-content-value" style={currentStyle}>{this.props.value}</span>
          {
            this.props.unit === '' ? null : (<span>{this.props.unit}</span>)
          }
        </div>
        <div className="single-info-footer">{this.props.desc}</div>
      </div>
    );
  }

  render() {
    return (
      this.props.loading
        ? (
            <div ref="container" className="single-info-cell" style={this.props.style}>
              <DefaultLoadingElement height={this.state.animatedHeight} />
            </div>
        ) : (
          this.props.error
            ? (
                <div ref="container" className="single-info-cell" style={this.props.style}>
                  <DefaultErrorElement height={this.state.animatedHeight} />
                </div>
            ) : (
              this.props.link ? (
                <a href={this.props.link} style={{color:'#fff'}}>
                {
                  this.renderBody()
                }
                </a>
              ) : this.renderBody()
            )
        )
    );
  }
}

SingleInfoCell.defaultProps = {
  iconClass:'icon-clock',
  title:'平均执行时间',
  value:'944',
  unit:'ms',
  desc:'影响用户数：934895',
  style:{},
  link:null,
  loading:false,
  error:null
}
